import {
	IN8nHttpFullResponse,
	INodeExecutionData,
	type IExecuteFunctions,
	type INodeType,
	type INodeTypeDescription,
} from 'n8n-workflow';
import { dataCache } from './util';

export class RespNode implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'UNC响应器',
		name: 'uncResponse',
		icon: 'file:webhook.svg',
		group: ['transform'],
		version: 1,
		description: 'UNC响应器',
		defaults: {
			name: 'UNC Response',
		},
		inputs: ['main'],
		outputs: ['main'],
		properties: [
			{
				displayName: '缓存请求参数',
				name: 'cacheParams',
				type: 'boolean',
				default: false,
			},
			{
				displayName: '缓存过期时间',
				name: 'cacheTTL',
				type: 'number',
				required: true,
				displayOptions: {
					show: {
						cacheParams: [
							true,
						],
					},
				},
				default: 60,
				placeholder: '请输入缓存过期时间',
			},
		],
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items = this.getInputData();
		let itemIndex = 0;
		const cacheParams = this.getNodeParameter('cacheParams', 0) as boolean;
		if (cacheParams) { // 缓存任务参数
			const cacheTTL = this.getNodeParameter('cacheTTL', 0) as number;
			const ttl = Math.max(cacheTTL, 0);
			// 直接写入缓存
			const key = this.getExecutionId() + '';
			const value = JSON.stringify(this.getInputData(itemIndex)?.[0]?.json);
			dataCache.set(key, value, ttl);
		}
		try {
			const result = { executeId: this.getExecutionId() };
			const response: IN8nHttpFullResponse = {
				body: JSON.stringify(result),
				statusCode: 200,
				headers: {
					'Content-Type': 'application/json',
				}
			};
			this.sendResponse(response);
		} catch (error) {
			// This node should never fail but we want to showcase how
			// to handle errors.
			if (this.continueOnFail()) {
				items.push({ json: this.getInputData(itemIndex)[0].json, error, pairedItem: itemIndex });
			} else {
				// Adding `itemIndex` allows other workflows to handle this error
				if (error.context) {
					// If the error thrown already contains the context property,
					// only append the itemIndex
					error.context.itemIndex = itemIndex;
				}
				throw error;
			}
		}
		return [items];
	}

}
